package com.student.xujiang.myallstudent.eventbus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.student.xujiang.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EventBusSendActivity extends AppCompatActivity {

    boolean isFirstFlag = true;

    @BindView(R.id.bt_eventbus_send_main)
    Button btEventbusSendMain;
    @BindView(R.id.bt_eventbus_send_sticky)
    Button btEventbusSendSticky;
    @BindView(R.id.tv_eventbus_send_resul)
    TextView tvEventbusSendResul;
    @BindView(R.id.activity_event_bus_send)
    RelativeLayout activityEventBusSend;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_bus_send);
        ButterKnife.bind(this);



    }

    //  13 、接收粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void StickyEventBus(StickyEvent event){
        tvEventbusSendResul.setText(event.msg);
    }



    @OnClick({R.id.bt_eventbus_send_main, R.id.bt_eventbus_send_sticky})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_eventbus_send_main:

                //4 、发送消息
                EventBus.getDefault().post(new MessageEvent("主线程发送过来的数据"));
                //结束当前页面
                finish();

                break;
            case R.id.bt_eventbus_send_sticky:
                if(isFirstFlag) {
                    isFirstFlag =false;
                    // 14、注册(注册一次  多次注册会崩溃)
                    EventBus.getDefault().register(EventBusSendActivity.this);
                }

                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 15、解注册
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(EventBusSendActivity.this);
    }


}
